<template>
  <el-dialog :title="dialogTitle" :visible="dialogShow" @close="handleClose" class="dia-box">
    <el-form :rules="rules" :model="form" label-width="100px" ref="formRef">
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          accept=".jpg, .jpeg, .png"
          action
          :auto-upload="false"
          :show-file-list="false"
          
          :on-change="getFile"
        >
          <div class="user-head-container">
            <img v-if="form.avatar" :src="$format_img(form.avatar)" class="avatar" />
            <!-- <img v-if="$store.state.user.userInfo.avatar" :src="$store.state.user.userInfo.avatar" class="avatar" /> -->
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <!-- <div class="text">修改</div> -->
          </div>
        </el-upload>
      </el-form-item>
       <el-form-item label="角色" prop="role_id" >
        <el-select v-model="form.role_id" @change="onRoleChange" :disabled="isDisabledRole">
          <el-option
            v-for="option in roleOptions"
            :key="option.role_id"
            :label="option.name"
            :value="option.role_id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="评委账号" prop="account">
        <el-input v-model="form.account" placeholder="输入评委账号" :disabled="isDisabled"  maxlength="10" />
      </el-form-item>
      <el-form-item label="评委名称" prop="username">
        <el-input v-model="form.username" placeholder="输入评委名称" />
      </el-form-item>
      <el-form-item label="密码"  v-if="dialogTitle ==='编辑'">
        <el-input v-model="form.password" placeholder="输入密码" />
      </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogTitle ==='新增'">
        <el-input v-model="form.password" placeholder="输入密码" maxlength="20"/>
      </el-form-item>
     
      <el-form-item label="电话号码" prop="telephone">
        <el-input v-model="form.telephone" placeholder="输入电话号码" />
      </el-form-item>
      <el-form-item label="真实实名" prop="realname">
        <el-input v-model="form.realname" placeholder="输入真实姓名" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { uploadAvatar, accountAdd, accountEdit ,accountList} from "@/api/account";
import { getRoleList } from "@/api/role";

import { getBase64 } from "@/utils/index.js";
export default {
  name: "EditDialog",
  props: {
    dialogShow: {
      type: Boolean,
      required: true
    },
    data: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      form: {
        account_id: "",
        avatar: "",
        account: "",
        username: "",
        role_id: null,
        password: "",
        realname: "",
        telephone: "",
        status:0
      },
      rules: {
        username: [
          { required: true, message: "请填写评委名称", trigger: "blur" },
          { min: 1, max: 10, message: "字符长度在 1 到 10 个字符", trigger: "blur" }
        ],
        account: [
          { required: true, message: "请填写评委账号", trigger: "blur" },
          { min: 10, max: 10, message: "账号长度必须为10个字符", trigger: "blur" }
        ],
        role_id: [{ required: true, message: "请选择角色", trigger: "blur" }],
        password: [
          { required: true, message: "请填写密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "密码长度在 6 到 20 个字符",
            trigger: "blur"
          }
        ]
      },
      roleOptions: [],
      cachedAccounts: [], // 用于缓存账号列表
     
    };
  },
  computed: {
    dialogTitle() {
      return this.data.account ? "编辑" : "新增";
    },
    isDisabled() {
      return (this.data.account && this.data.account.length ===10) ? true : false;
     
    },
    isDisabledRole(){
     return (this.data.role_id === 2 )? true : false;
    }
  },
  watch: {
    data: {
      handler(newData) {
        if (newData) {
          this.form = {
            ...this.data,
            role_id: this.data.role_id || "",
            account_id: this.data.id,
            status:this.data.status ||0
          };
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    getRoleList().then(res => {
      this.roleOptions = res.list;
    });
    this.loadCachedAccounts();
  },
  methods: {
   // 获取所有账号列表并缓存
    async loadCachedAccounts() {
      this.cachedAccounts = await this.getAllAccounts();
     
    },
   // 获取所有账号列表
  async getAllAccounts() {
    let allAccounts = [];
    let params = { page: 1, limit: 10 };

    try {
      const res = await accountList(params);
      if (!res || !res.list || res.list.length === 0) {
        console.warn('No accounts found.');
        return allAccounts;
      }

      const totalPages = res.totalPages || Math.ceil(res.totalCount / params.limit);
      allAccounts = [...allAccounts, ...res.list];

      for (let page = 2; page <= totalPages; page++) {
        params.page = page;
        const res = await accountList(params);
        allAccounts = [...allAccounts, ...res.list];
      }
    } catch (error) {
      console.error('Failed to fetch accounts:', error);
    }

    return allAccounts;
  },

  // 角色变更时触发
    onRoleChange(roleId) {
      if (roleId === 2) { // 假设评委角色的ID为 2
        let uniqueAccount = this.generateAccount();
        const existingAccounts = this.cachedAccounts; // 使用已缓存的账号列表
        
        // 查重
        while (existingAccounts.some(account => account.account === uniqueAccount)) {
          uniqueAccount = this.generateAccount();
        }

        this.form.account = uniqueAccount;
       
      
      } else {
        this.form.account = this.data.account ;
       
      }
    },

  // 生成账号的方法
  generateAccount() {
    const prefix = 'pw';
    let randomPart = '';
    for (let i = 0; i < 8; i++) {
      randomPart += Math.floor(Math.random() * 10); // 生成0-9之间的随机数
    }
    return prefix + randomPart;
  },


    // 修改用户头像
    getFile(file) {
      if (this.beforeAvatarUpload(file.raw)) {
        const formData = new FormData();
        formData.append("file", file.raw);
          uploadAvatar(formData).then(result => {
            this.form.avatar = result.avatar;
            
          });
        
      }
    },
    beforeAvatarUpload(file) {
      let types = ["image/jpeg", "image/jpg", "image/png"];
      const isImage = types.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 3;

      if (!isImage) {
        this.$toast("上传图片只能是 jpeg、 jpg、 png格式!");
      }
      if (!isLt2M) {
        this.$toast("上传图片大小不能超过 3MB!");
      }
      return isImage && isLt2M;
    },
    handleClose() {
      this.$emit("update:dialogShow", false);
      this.resetForm();
    },
    handleSubmit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.data.id) {
            accountEdit(this.form).then(res => {
              this.$emit("update:dialogShow", false);
              this.$message.success("编辑成功");
              this.$emit("onUpdate");
              this.resetForm();
            });
          } else {
            accountAdd(this.form).then(res => {
              this.$emit("update:dialogShow", false);
              this.$message.success("新增成功");
              this.$emit("onUpdate");
              this.resetForm();
            });
          }
        } else {
          console.log("验证失败");
        }
      });
    },
    resetForm() {
     // 确保在数据变化后DOM能够及时更新
     
      this.form = {
        account_id: "",
        avatar: "",
        account: "",
        username: "",
        role_id: null,
        password: "",
        realname: "",
        telephone: "",
        status:0
      };
       
     
     
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.avatar-uploader .el-upload {
  border-radius: 45px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 90px;
  height: 90px;
  border-radius: 45px;
  line-height: 90px;
  text-align: center;
  border: 1px solid #000;
}
.avatar {
  width: 90px;
  height: 90px;
  display: block;
  border-radius: 50%;
}
.dia-box ::v-deep .el-dialog {
  width: 640px;
  border-radius: 14px;
}
</style>